package main;

import com.primavera.integration.client.Session;
import main.Primavera.PrimaveraOpenProject;
import main.SQL.OpenSQLProject;
import main.Trees.OpenProjectTreeRender;
import main.Trees.ProjectNode;

import javax.swing.*;
import javax.swing.tree.DefaultTreeModel;
import java.awt.*;

/* OpenProjectDialog - фрейм выбора проекта для открытия */

public class OpenProjectDialog extends javax.swing.JDialog {

    private Session session;
    public ProjectNode curProject;

    //region OpenProjectDialog(java.awt.Frame parentFrame, boolean modal, Session session) - конструктор класса
    public OpenProjectDialog(java.awt.Frame parentFrame, boolean modal, Session session) {
        super(parentFrame, modal);
        this.session = session;

        initComponents();
        centerOnScreen(this);

        loadProjects();
    }
    //endregion

    //region centerOnScreen(Container win) - центрирование фрейма, вызов из конструктора
    private void centerOnScreen(Container win) {
        GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
        Rectangle bounds = gd.getDefaultConfiguration().getBounds();
        Dimension winDim = win.getSize();
        Point loc = new Point((bounds.width - winDim.width) / 2, (bounds.height - winDim.height) / 2);
        win.setLocation(loc);
    }
    //endregion
  
    private void loadProjects() {
        ProjectNode root;

        if ( session != null )
            root = synchProject();
        else
            root = openSqlProject();

        DefaultTreeModel model = new DefaultTreeModel(root, true);
        jTree1.setModel(model);
        jTree1.setRootVisible(true);

    }

    private ProjectNode synchProject() {
        ProjectNode root = new PrimaveraOpenProject(session).getRoot();
        setTitle("Выбор проекта для синхронизации");
        jLabel1.setText("Выберите проект для синхронизации");

        return root;
    }

    private ProjectNode openSqlProject() {
        ProjectNode root = new OpenSQLProject().getRoot();
        setTitle("Открыть проект");
        jLabel1.setText("Выберите проект для назначения связей");

        return root;
    }

    private void jTree1ValueChanged(javax.swing.event.TreeSelectionEvent evt) {

        ProjectNode node = (ProjectNode) jTree1.getLastSelectedPathComponent();

        if (node == null) return;

        if(node.isTask()) {
            buttonOpen.setEnabled(true);
        } else {
            buttonOpen.setEnabled(false);
        }
    
    }

    private void buttonOpenActionPerformed() {
        if (jTree1.getLastSelectedPathComponent() == null) return;

        this.curProject = (ProjectNode) jTree1.getLastSelectedPathComponent();
        dispose();
    }

    private void jTree1MouseClicked(java.awt.event.MouseEvent evt) {

        if (evt.getClickCount() == 2) {
            ProjectNode node = (ProjectNode) jTree1.getLastSelectedPathComponent();

            if (node == null || !node.isTask())
            return;

            this.curProject = node;
            dispose();
        }
    
    }

    private void initComponents() {

        JPanel jPanel1 = new JPanel();
        JButton jButton1 = new JButton();
        jLabel1 = new JLabel();
        JSeparator jSeparator1 = new JSeparator();
        JScrollPane jScrollPane1 = new JScrollPane();
        jTree1 = new javax.swing.JTree();
        buttonOpen = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jButton1.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        jButton1.setText("Отмена");
        jButton1.setMargin(new java.awt.Insets(6, 14, 6, 14));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                dispose();
            }
        });

        jLabel1.setFont(new java.awt.Font("Segoe UI Light", 0, 18)); // NOI18N
        jLabel1.setText("Откройте проект в Primavera P6");

        jSeparator1.setBackground(java.awt.SystemColor.control);
        jSeparator1.setForeground(java.awt.SystemColor.activeCaptionBorder);

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("Primavera P6 EPS Structure");
        jTree1.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        jTree1.setRowHeight(18);
        jTree1.setShowsRootHandles(true);
        jTree1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTree1MouseClicked(evt);
            }
        });
        jTree1.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                jTree1ValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jTree1);

        buttonOpen.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        buttonOpen.setText("Выбрать");
        buttonOpen.setEnabled(false);
        buttonOpen.setMargin(new java.awt.Insets(6, 14, 6, 14));
        buttonOpen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonOpenActionPerformed();
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jSeparator1)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(56, 56, 56)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addGroup(jPanel1Layout.createSequentialGroup()
                                                .addComponent(buttonOpen, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 488, Short.MAX_VALUE)
                                                .addComponent(jLabel1)))
                                .addGap(56, 56, 56))
        );
        jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(30, 30, 30)
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 326, Short.MAX_VALUE)
                                .addGap(29, 29, 29)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(buttonOpen, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(56, 56, 56))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();

        jTree1.setCellRenderer(new OpenProjectTreeRender());

    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration
    private JButton buttonOpen;
    private JTree jTree1;
    private JLabel jLabel1;
    // End of variables declaration
}
